import 'dart:async';
import 'dart:math';

import 'package:flutter_demo/models/user_model.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final asyncUserProvider = AsyncNotifierProvider<AsyncUserNotifier, UserModel?>(
  () => AsyncUserNotifier(),
);

class AsyncUserNotifier extends AsyncNotifier<UserModel?> {
  // /// 更新用户信息
  // void updateUser(UserModel newUser) => state = newUser;
  /// 登录
  void loginIn() async {
    try {
      // 使用 maybeWhen 提取 data 状态的值，其他状态默认返回 null
      final existingUser = state.maybeWhen(
        data: (value) => value,
        orElse: () => null,
      );
      print(existingUser.toString());
      if (existingUser != null) {
        print("已有用户信息，直接返回");
        return;
      }
      state = const AsyncValue.loading();
      final userModel = await _loadUserFromLocal();
      state = AsyncValue.data(userModel);
    } catch (e) {
      state = AsyncValue.error(e, StackTrace.current);
    }
  }

  /// 退出登录
  void logout() => state = const AsyncValue.data(null);

  /// 从本地加载用户信息
  Future<UserModel?> _loadUserFromLocal() async {
    final Random random = Random();
    await Future.delayed(const Duration(seconds: 2));
    int randomInt = random.nextInt(10);

    print(randomInt);

    if (randomInt > 5) {
      throw Exception("加载用户信息失败");
    } else {
      return UserModel.fromJson({
        'name': '张三',
        'age': 18,
        'emailAddress': 'zhangsan@example.com',
      });
    }
  }

  @override
  FutureOr<UserModel?> build() async {
    return null;

    // return await _loadUserFromLocal();
  }
}
